package com.yu.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yu.bean.User;
import com.yu.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/getAll")
	public String getAll(Model model) {
		List<User> list = userService.getAll();
		model.addAttribute("list", list);
		return "user/showList";
	}
	
	@RequestMapping("/toAdd")
	public String toAdd() {
		return "user/register";
	}
	
	@RequestMapping("/add")
	public String add(User user) {
		userService.add(user);
		return "user/login";
	}
	
	@RequestMapping("/delete")
	public String delete(int id) {
		userService.delete(id);
		return "forward:/user/getAll.do";
	}
	
	@RequestMapping("/toEdit")
	public String toEdit(Model model,int id) {
		User user = userService.getById(id);
		model.addAttribute("user", user);
		return "user/edit";
	}
	
	@RequestMapping("/edit")
	public String edit(User user) {
		userService.update(user);
		return "forward:/user/getAll.do";
	}
	
	@RequestMapping("/toLogin")
    public String toLogin() {
		return "user/login";
	}
	
	@RequestMapping("/login")
    public String login(Model model,User user) {
        int i = userService.doLogin(user);
        if (i > 0) {
        	model.addAttribute("msg", "登陆成功");
            return "redirect:/main.jsp";
        } else {
            model.addAttribute("msg", "账号或密码错误，请重新登陆!");
            return "user/login";
        }
    }
	
	@RequestMapping("/logout")
    public String logout() {
		return "user/login";
	}
	
	@RequestMapping("/checkName")
	@ResponseBody
	public String checkName(String username) {
		int i = userService.checkName(username);
		return i > 0 ? "error" : "success";
	}
}
